<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网页游戏</title>
    <style>
        /* 在这里添加CSS样式 */
        body {
            background-color: #323131;
        }

        #gameCanvas {
            border: 1px solid #000;
        }

    </style>
</head>
<body>
<!--<div id="map"></div>-->
<canvas id="gameCanvas" width="400" height="300"></canvas>
<!--<script src="game.js"></script>-->
<script>
  const canvas = document.getElementById('gameCanvas')
  const ctx = canvas.getContext('2d')

  const boxSize = 50
  // let x = canvas.width / 2;
  // let y = canvas.height / 2;
  let x = 0
  let y = 0

  function generateRandomMazeBak (width, height) {
    const map = []
    for (let i = 0; i < height; i++) {
      map[i] = []
      for (let j = 0; j < width; j++) {
        map[i][j] = Math.random() > 0.8 ? 1 : 0 // 生成一个随机地图，有80%的概率是障碍
      }
    }
    return map
  }






  function generateRandomMaze1(width, height) {
    const map = [];

    // 初始化地图，所有单元格都设置为0（空）
    for (let i = 0; i < height; i++) {
      map[i] = [];
      for (let j = 0; j < width; j++) {
        map[i][j] = 1;
      }
    }

    // 设置起点和初始化路径
    const startX = 0;
    const startY = 0;
    const endX = width - 1;
    const endY = height - 1;

    map[startY][startX] = 0; // 起点
    map[endY][endX] = 0; // 终点

    // 检查单元格是否在迷宫范围内的函数
    const isValidCell = (x, y) => x >= 0 && x < width && y >= 0 && y < height;

    // 检查单元格是否被墙包围的函数
    const isSurroundedByWalls = (x, y) =>
      isValidCell(x, y) &&
      (!isValidCell(x - 1, y) || map[y][x - 1] === 1) &&
      (!isValidCell(x + 1, y) || map[y][x + 1] === 1) &&
      (!isValidCell(x, y - 1) || map[y - 1][x] === 1) &&
      (!isValidCell(x, y + 1) || map[y + 1][x] === 1);

    // 初始化当前位置为起点
    let currentX = startX;
    let currentY = startY;

    // 从起点到终点创建一条路径
    while (currentX !== endX || currentY !== endY) {
      map[currentY][currentX] = 0; // 将当前单元格标记为路径的一部分

      // 确定有效的相邻单元格
      const neighbors = [];
      if (isValidCell(currentX - 1, currentY) && !isSurroundedByWalls(currentX - 1, currentY)) {
        neighbors.push({ x: currentX - 1, y: currentY });
      }
      if (isValidCell(currentX + 1, currentY) && !isSurroundedByWalls(currentX + 1, currentY)) {
        neighbors.push({ x: currentX + 1, y: currentY });
      }
      if (isValidCell(currentX, currentY - 1) && !isSurroundedByWalls(currentX, currentY - 1)) {
        neighbors.push({ x: currentX, y: currentY - 1 });
      }
      if (isValidCell(currentX, currentY + 1) && !isSurroundedByWalls(currentX, currentY + 1)) {
        neighbors.push({ x: currentX, y: currentY + 1 });
      }

      // 随机选择一个相邻单元格进行移动
      const randomNeighbor = neighbors[Math.floor(Math.random() * neighbors.length)];
      if (randomNeighbor) {
        currentX = randomNeighbor.x;
        currentY = randomNeighbor.y;
      } else {
        // 如果没有有效的相邻单元格，则回溯到上一个单元格
        map[currentY][currentX] = 1; // 将当前单元格标记为墙
        const lastPosition = path.pop();
        if (!lastPosition) break; // 如果回溯到起点，则跳出循环
        currentX = lastPosition.x;
        currentY = lastPosition.y;
      }
    }

    return map;
  }



  function generateRandomMaze(width, height) {
    let map = [];

    // 初始化地图，所有单元格都设置为1（墙）
    for (let i = 0; i < height; i++) {
      map[i] = [];
      for (let j = 0; j < width; j++) {
        map[i][j] = 1;
      }
    }
    console.info('init', map)

    // 设置起点和初始化路径
    const startX = 0;
    const startY = 0;
    const endX = width - 1;
    const endY = height - 1;

    map[startY][startX] = 0; // 起点
    map[endY][endX] = 0; // 终点

    // 检查单元格是否在迷宫范围内的函数
    const isValidCell = (x, y) => x >= 0 && x < width && y >= 0 && y < height;

    // 创建一个访问过的集合
    const visited = new Set();

    // 深度优先搜索生成路径
    function dfs(x, y) {
      if (!isValidCell(x, y) || visited.has(`${x},${y}`)) {
        return;
      }

      map[y][x] = 0; // 标记当前单元格为路径
      visited.add(`${x},${y}`);

      const neighbors = [
        { x: x - 1, y: y },
        { x: x + 1, y: y },
        { x: x, y: y - 1 },
        { x: x, y: y + 1 },
      ];

      // 打乱邻居的顺序
      neighbors.sort(() => Math.random() - 0.5);

      for (const neighbor of neighbors) {
        dfs(neighbor.x, neighbor.y);
      }
    }

    dfs(startX, startY);

    return map;
  }






  function drawMap (map) {
    // console.info('map', x, y)
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    for (let i = 0; i < map.length; i++) {
      for (let j = 0; j < map[i].length; j++) {
        if (map[i][j] === 1) {
          ctx.fillStyle = 'black'
          ctx.fillRect(j * boxSize, i * boxSize, boxSize, boxSize)
        } else {
          ctx.fillStyle = 'green'
          ctx.fillRect(j * boxSize, i * boxSize, boxSize, boxSize)
        }
      }
    }
  }

  function draw () {
    // console.info('move', x, y)
    // drawMap(map); // 绘制新的地图
    // ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'blue'
    ctx.fillRect(x, y, boxSize, boxSize)
  }

  const map = generateRandomMaze(canvas.width / boxSize, canvas.height / boxSize)
  console.info('map', map)
  drawMap(map)
  draw()

  document.addEventListener('keydown', (e) => {
    let newX = x
    let newY = y

    switch (e.key) {
      case 'ArrowUp':
        newY -= boxSize
        break
      case 'ArrowDown':
        newY += boxSize
        break
      case 'ArrowLeft':
        newX -= boxSize
        break
      case 'ArrowRight':
        newX += boxSize
        break
      default:
        return
    }

    // console.info(newX, newY)
    if (newX < 0 || newX + boxSize > canvas.width || newY < 0 || newY + boxSize > canvas.height) {
      alert('已超出画布边界！')
    } else if (map[Math.floor(newY / boxSize)][Math.floor(newX / boxSize)] === 1) {
      alert('碰到障碍了！')
      x = 0
      y = 0
      drawMap(map)
      draw()
    } else {
      x = newX
      y = newY
      drawMap(map)
      draw()
    }
  })

  /*








  */


</script>
</body>
</html>
